package com.jm.day24.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils {

    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    /**获取连接池
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }


    /**
     * 从连接池中获取连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }

    /**释放资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public static void closeResource(Connection conn, Statement stmt, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (Exception e) {
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (Exception e) {
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 开启事务
     * @throws SQLException
     */
    public static void startTransaction() throws SQLException{
        Connection conn = getConnection();
        conn.setAutoCommit(false);
        tl.set(conn);
    }

    /**
     * 提交事务并关闭
     */
    public static void commitAndClose(){
        Connection conn = getTxConnection();
        DbUtils.commitAndCloseQuietly(conn);
        //清除已经关闭的连接对象
        tl.remove();
    }

    /**
     * 回滚事务并关闭
     */
    public static void rollbackAndClose(){
        Connection conn = getTxConnection();
        DbUtils.rollbackAndCloseQuietly(conn);
        //清除已经关闭的连接对象
        tl.remove();
    }

    /**
     * 获取共享的连接对象，这个连接对象是已经开启了事务的
     */
    public static Connection getTxConnection(){
        return tl.get();
    }

}